package cn.exrick.xboot.modules.content.serviceimpl;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.utils.RestTemplateUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.config.properties.RestTemplateProperties;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentIndexVo;
import cn.exrick.xboot.modules.base.dao.DepartmentDao;
import cn.exrick.xboot.modules.base.entity.Department;
import cn.exrick.xboot.modules.content.dao.*;
import cn.exrick.xboot.modules.content.dao.mapper.HontUserMapper;
import cn.exrick.xboot.modules.content.dao.mapper.HontUserRoleMapper;
import cn.exrick.xboot.modules.content.entity.*;
import cn.exrick.xboot.modules.content.service.HontUserService;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.thymeleaf.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 娴嬭瘯接口实现
 * @author Exrick
 */
@Slf4j
@Service
@Transactional
public class HontUserServiceImpl implements HontUserService {

    @Autowired
    private HontUserDao hontUserDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private HontUserPostDao hontUserPostDao;

    @Autowired
    private HontPostDao hontPostDao;

    @Autowired
    private HontUserRoleDao hontUserRoleDao;
    @Autowired
    private SecurityUtil securityUtil;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public HontUserDao getRepository() {
        return hontUserDao;
    }

    @Override
    public Page<HontUser> findByCondition(HontUser hontUser, SearchVo searchVo, Pageable pageable) {

        return hontUserDao.findAll(new Specification<HontUser>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<HontUser> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<String> usernameField = root.get("userName");
                Path<String> mobileField = root.get("mobile");
                Path<String> emailField = root.get("email");
                Path<String> departmentIdField = root.get("departmentId");
                Path<String> sexField=root.get("sex");
                Path<Integer> typeField=root.get("type");
                Path<Integer> statusField=root.get("status");
                Path<Date> createTimeField = root.get("createTime");
                Path<String> nickname = root.get("nickName");
                Path<String> postId = root.get("postId");
               /* Path<List<HontRole>> roles = root.get("roles");*/
                /*Path<String> roleId = root.get("roleId");*/
                List<Predicate> list = new ArrayList<Predicate>();
                //姓名
                if(!StringUtils.isEmpty(hontUser.getNickName())){
                    list.add(cb.or(cb.like(nickname, '%' + hontUser.getNickName() + '%'),cb.like(mobileField,'%'+hontUser.getNickName()+'%')));
                }
                /*if(StrUtil.isNotBlank(hontUser.getDepartmentId())){
                    list.add(cb.equal(departmentIdField, hontUser.getDepartmentId()));
                }
                if(StrUtil.isNotBlank(hontUser.getPostId())){
                    list.add(cb.equal(departmentIdField, hontUser.getPostId()));
                }*/
                /*if(StrUtil.isNotBlank(hontUser.getRoleId())){
                    list.add(cb.equal(roleId, hontUser.getRoleId()));
                }*/

                /*if(roles != null){
                    Path<String> roleId = roles.get("id");
                    List<HontRole> rolesIds = hontUser.getRoles();
                    for (int i = 0; i < rolesIds.size(); i++){
                        String id = rolesIds.get(i).getId();
                        list.add(cb.equal(roleId, id));
                    }
                }*/




                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

    @Override
    public HontUser findByUserName(String username) {
        HontUser hontUser = hontUserDao.findByUserName(username);
        if (hontUser == null){
            return null;
        }
        // 关联部门
        if(StrUtil.isNotBlank(hontUser.getDepartmentId())){
            Department department = departmentDao.findById(hontUser.getDepartmentId()).orElse(null);
            if(department!=null){
                hontUser.setDepartmentTitle(department.getTitle());
            }
        }
        //关联岗位
        List<HontUserPost> byHontUserPost = hontUserPostDao.findByHontUserId(hontUser.getId());
        if (byHontUserPost.size() > 0) {
            List<String> postIds = new ArrayList<>();
            for (int i = 0; i < byHontUserPost.size(); i++) {
                HontPost hontPost = hontPostDao.findById(byHontUserPost.get(i).getHontPostId()).orElse(null);
                postIds.add(hontPost.getId());
            }
            hontUser.setPostIds(postIds);
        }
        // 关联角色
        HontUserRole byHontUserId = hontUserRoleDao.findByHontUserId(hontUser.getId());
        hontUser.setRoleId(byHontUserId.getHontRoleId());
        // 关联权限菜单
        /*List<HontPermission> permissionList = hontPermissionMapper.findByHontUserId(hontUser.getId());
        hontUser.setPermissions(permissionList);*/
        return hontUser;
    }

    @Override
    public HontUser findByMobile(String mobile) {
        return hontUserDao.findByMobile(mobile);
    }

    @Override
    public HontUser findByEmail(String email) {
        return hontUserDao.findByEmail(email);
    }

    @Override
    public List<HontUser> findByDepartmentId(String departmentId) {
        return hontUserDao.findByDepartmentId(departmentId);
    }

    @Override
    public HontUser cutomerfindByMobile(String mobile) {
        List<HontUser> all = hontUserDao.findAll();
        HontUser user = null;
        for(int i=0;i<all.size();i++){
            log.info(all.get(i).getMobile());
            if(all.get(i).getMobile()!=null&&all.get(i).getMobile().equals(mobile)){
                boolean equals = all.get(i).getMobile().equals(mobile);
                log.info(""+equals);
                break;
            }
        }

        //  User user = userDao.findByMobile(mobile);
        if(user==null){
            return null;
        }
        // 关联部门
        if(StrUtil.isNotBlank(user.getDepartmentId())){
            Department department = departmentDao.findById(user.getDepartmentId()).orElse(null);
            if(department!=null){
                user.setDepartmentTitle(department.getTitle());
            }
        }
        /*// 关联角色
        List<HontRole> roleList = userRoleMapper.findByUserId(user.getId());
        user.setRoles(roleList);
        // 关联权限菜单
        List<Permission> permissionList = permissionMapper.findByUserId(user.getId());
        user.setPermissions(permissionList);*/
        return user;
    }

    @Override
    public HontUser findByNickName(String nickName) {
        return hontUserDao.findByNickName(nickName);
    }

    @Override
    public HontUser findById(String userId) {
        return hontUserDao.findById(userId).orElse(null);
    }

    @Override
    public List<HontUser> findByPostId(String postId) {
        return hontUserDao.findByPostId(postId);
    }

    @Override
    public Result<HontUser> addHontUser(HontUser u,String roles,String[] postId) throws Exception {


        if (u.getType() == 1){
            if(StrUtil.isBlank(u.getUserName()) || StrUtil.isBlank(u.getPassWord())){
                return ResultUtil.error("缺少必需表单字段");
            }
            if (hontUserDao.findByUserName(u.getUserName()) != null) {
                return ResultUtil.error("该账户已被注册");
            }
            String password = new BCryptPasswordEncoder().encode(u.getPassWord());
            u.setPassWord(password);
        }
        if (u.getType() == 0){
            if(StrUtil.isBlank(u.getMobile())){
                return ResultUtil.error("缺少必需表单字段");
            }
            if (hontUserDao.findByMobile(u.getMobile()) != null) {
                return ResultUtil.error("该手机号已被注册");
            }
            String pwd = u.getMobile();
            String s = "hk" + pwd.substring(pwd.length() - 6, pwd.length());
            String password = new BCryptPasswordEncoder().encode(s);
            u.setUserName(pwd);
            u.setPassWord(password);
        }

        u.setApprove(CommonConstant.ING);
        u.setDepartmentCopyId(u.getDepartmentId());
        u.setDepartmentId(u.getDepartmentId());
        HontUser hontUser = hontUserDao.save(u);


        if (hontUser == null) {
            return ResultUtil.error("添加失败");
        }
        //添加岗位
        if (postId.length > 0){
            for (int i = 0; i < postId.length; i++) {
                HontUserPost hontUserPost = new HontUserPost();
                hontUserPost.setHontPostId(postId[i]);
                hontUserPost.setHontUserId(hontUser.getId());
                hontUserPostDao.save(hontUserPost);
            }
        }
        if (StrUtil.isNotBlank(roles)) {
            //添加角色
            HontUserRole ur = new HontUserRole();
            ur.setHontUserId(hontUser.getId());
            ur.setHontRoleId(roles);
            hontUserRoleDao.save(ur);
        }
        return ResultUtil.data(hontUser);
    }

    public int batchInsert(List<HontUser> hontUsers) {
        StringBuilder sb = new StringBuilder();
        String nickName = securityUtil.getCurrUser().getNickName();
        sb.append("INSERT INTO hont_user(id,avatar, mobile, nick_name, pass_word, status, type,user_name, department_id, create_by, del_flag, approve, is_backstage, create_time) VALUES ");
        for(HontUser hontUser : hontUsers) {
            sb.append("(REPLACE(UUID(),\"-\",\"\"),?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now()),");
        }
        String sql = sb.toString().substring(0, sb.length() - 1);
        log.info("sql",sql);
        Query query = entityManager.createNativeQuery(sql);
        int paramIndex = 1;
        for(HontUser hontUser : hontUsers) {
            query.setParameter(paramIndex++, "https://i.loli.net/2019/04/28/5cc5a71a6e3b6.png");
            query.setParameter(paramIndex++, hontUser.getMobile());
            query.setParameter(paramIndex++, hontUser.getNickName());
            query.setParameter(paramIndex++, hontUser.getPassWord());
            query.setParameter(paramIndex++, 0);
            query.setParameter(paramIndex++, 0);
            query.setParameter(paramIndex++, hontUser.getUserName());
            query.setParameter(paramIndex++, hontUser.getDepartmentId());
            query.setParameter(paramIndex++, nickName);
            query.setParameter(paramIndex++, 0);
            query.setParameter(paramIndex++, 1);
            query.setParameter(paramIndex++, 0);
        }
        return query.executeUpdate();
    }

    @Override
    public List<HontUser> findByApprove(Integer approve) {
        return hontUserDao.findByApprove(approve);
    }

    @Override
    public List<HontUser> findByDepartmentIdLike(String departmentId) {
        return hontUserDao.findByDepartmentIdLike(departmentId);
    }
}